package com.project.database;

import com.project.model.ColumnData;
import com.project.util.JdbcUtil;
import lombok.SneakyThrows;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DataBaseData {

    private JdbcUtil jdbcUtil;

    private Connection connection;

    private List<TableData> tables;

    private String databaseName;

    public String getDatabaseName() {
        return databaseName;
    }


    public DataBaseData(String driver, String url, String username, String password) {
        this.jdbcUtil = new JdbcUtil(driver, url, password, username);
        this.connection = this.jdbcUtil.getConnection();
        init();
    }

    private void init() {
        this.setTables();
    }

    @SneakyThrows
    private void setTables() {
        // 懒加载表列表
        tables = new ArrayList<>();

        // 获取数据库信息
        DatabaseMetaData metaData = this.connection.getMetaData();
        String catalog = this.connection.getCatalog();
        this.databaseName = catalog;

        // 获取数据库表
        ResultSet res = metaData.getTables(catalog, null, null, new String[]{"TABLE"});
        while ( res.next() ){
            // 获取表信息
            String table_name = (String) res.getObject("TABLE_NAME");
            ResultSet columns = metaData.getColumns(catalog, null, table_name, "%");
            TableData tableData = new TableData(table_name);
            while ( columns.next() ){
                // 使用到的信息 字段名-字段类型-字段大小-字段备注
                String column_name = columns.getString("COLUMN_NAME");
                String type_name = columns.getString("TYPE_NAME");
                Long column_size = columns.getLong("COLUMN_SIZE");
                String remarks = columns.getString("REMARKS");
                ColumnData columnData = new ColumnData(column_name, column_size, type_name, remarks);
                tableData.addColumnData(columnData);
                tableData.addColumn(column_name);
            }

            // 获取表主键信息
            ResultSet primaryKeysRes = metaData.getPrimaryKeys(catalog, null, table_name);
            while ( primaryKeysRes.next() ){
                String column_name = primaryKeysRes.getString("COLUMN_NAME");
                tableData.setPrimaryKey(column_name);
                break;
            }
            this.tables.add(tableData);
        }
    }

    public List<TableData> getTables() {
        return tables;
    }
}
